package com.woyou.utils;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

public class JsonUtils {

	public synchronized static <T> T getInstance(Class<T> arg0, JSONObject jsonObject){
		try {
			T  t =  arg0.newInstance();
			Field[] fields = arg0.getFields();
			for(Field field : fields){
				
				if( !jsonObject.has(field.getName()) )
				     continue;
				
				if(jsonObject.get(field.getName())!=JSONObject.NULL){
				
					Class<?> type = field.getType();
					if((type.isPrimitive() || type.isAssignableFrom(String.class)) && !type.isArray())
					{
//						Object o = jsonObject.get(field.getName());
//						if(o != JSONObject.NULL)
//						{
							field.set(t, jsonObject.get(field.getName()));
//							field.set(t, o);
//						}
					} 
					else if (type.isArray()) {
						JSONArray jSONArray = jsonObject.getJSONArray(field.getName());
						
						Class<?> componentType = type.getComponentType();
						int length = jSONArray.length();
						Object array = Array.newInstance(componentType, length);
						for (int i = 0; i < length; i++) {
	
							if (componentType.isPrimitive()
									|| componentType.isAssignableFrom(String.class)) {
								Array.set(array, i, jSONArray.get(i));
							} else {
								Array.set(array, i, getInstance(componentType,
										jSONArray.getJSONObject(i)));
							}
						}
						field.set(t, array);
					} else {
						field.set(t, getInstance(type, jsonObject
								.getJSONObject(field.getName())));
					}
				}
			}
			return t;
		} catch (Exception e) {
			Log.e("error", e.getMessage(), e);
		}
		return null;
	}
	
	public synchronized static <T> List<T> getInstance(Class<T> arg0, JSONArray jSONArray){
		try {
			List<T> result = new ArrayList<T>();
			int length = jSONArray.length();
			for(int i = 0; i<length;i++){
				result.add(getInstance(arg0,jSONArray.getJSONObject(i)));
			}
			return result;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}
//	
//	private static void setVaule(Field field,JSONObject jsonObject, Object instance){
//		if(field.getType().isPrimitive()){
//			
//		}
//	}
}
